<template>
  <div class="pickEdit_dialog">
    <el-dialog
      :title="title"
      :width="width"
      :height="height"
      :visible.sync="pickDialogShow"
      :before-close="handleClose"
    >
      <div class="pickEdit_content">
        <div class="addBtn">
          <el-button
            type="text"
            @click="addPick()"
            style="text-decoration: underline"
            v-hasPermi="['business:pickLimit:add']"
          >
            +添加一条
          </el-button>
        </div>
        <div class="pickEdit_table">
          <el-table
            :data="tableData"
            row-key="id"
            border
            highlight-current-row=""
          >
            <el-table-column
              v-for="(item,index) in columns"
              :key="index"
              :prop="item.prop"
              :label="item.label"
              :width="getColumnWidth(index,'columns')"
              show-overflow-tooltip
              align="center"
            >
               <template slot-scope="scope">
                <el-form :model="addOreditPickQueryObj[`form_'${scope.row['id']}`]" :rules="rules" ref="formRef" >
                    <!--产品限制单独处理 -->
                   <div v-if="item.prop === 'isProduct'">
                        <el-form-item 
                          v-if="scope.row['optionType']"
                          style="margin-bottom: 0;"
                          label="" prop="isProduct"
                          >
                          <el-select
                            v-model="addOreditPickQueryObj[`form_'${scope.row['id']}`].isProduct"
                            clearable
                            filterable
                            placeholder="请选择"
                            style="width: 100%"
                            @change="isProductChange($event,scope.row)"
                           >
                             <el-option
                              v-for="(item, index) in isProductOption"
                              :key="index"
                              :label="item.label"
                              :value="item.value"
                              ></el-option>
                           </el-select>

                        </el-form-item>
                        <span v-else>{{ ArrayFormatObj(isProductOption)[scope.row[item.prop]]}}</span>
                   </div>
                   <!--产品限制集合单独处理  -->
                   <div v-else-if="item.prop === 'productIds'">
                        <el-form-item 
                          style="margin-bottom: 0;"
                          label="" prop="productIds"
                          >
                          <el-select
                            v-if="scope.row['optionType']"
                           v-model="addOreditPickQueryObj[`form_'${scope.row['id']}`].productIds"
                           multiple
                           collapse-tags
                           clearable
                           filterable
                           placeholder="请选择"
                           style="width: 100%"
                           :disabled="addOreditPickQueryObj[`form_'${scope.row['id']}`].isProduct == 0"
                          >
                            <el-option
                             v-for="(item, index) in productIdsOption"
                             :key="index"
                             :label="item.productName"
                             :value="item.id.toString()"
                             ></el-option>
                          </el-select>
                          <el-select
                           v-else
                           v-model="scope.row[item.prop]"
                           multiple
                           collapse-tags
                           clearable
                           filterable
                           placeholder="请选择"
                           style="width: 100%"
                           :disabled="true"
                          >
                            <el-option
                             v-for="(item, index) in productIdsOption"
                             :key="index"
                             :label="item.productName"
                             :value="item.id.toString()"
                             ></el-option>
                          </el-select>
                        </el-form-item>
                   </div>
                   <!--操作单独处理  -->
                   <div v-else-if="item.prop === 'operation'">
                    <el-button
                      type="text"
                      v-if="scope.row['optionType']"
                      @click="handelSave(scope.row,addOreditPickQueryObj[`form_'${scope.row['id']}`])"
                      >保存</el-button
                    >
                    <el-button
                      type="text"
                      v-if="!scope.row['optionType']"
                      @click="handelEdit(scope.row)"
                      v-hasPermi="['business:pickLimit:edit']"
                      >编辑</el-button
                    >
                    <el-popconfirm
                     v-if="!scope.row['optionType']"
                     title="确定要删除该限制吗？"
                     style="margin-left: 10px"
                     @cancel="hanCancelDel"
                     @confirm="handelDel(scope.row)"
                   >
                      <el-button 
                      slot="reference"
                      type="text"
                      style="color: #ff116e"
                      v-hasPermi="['business:pickLimit:remove']"
                      >删除</el-button>
                   </el-popconfirm>
                   </div>
                   <span v-else>
                     {{  scope.row[item.prop] }}
                   </span>
                </el-form>
               </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Sortable from "sortablejs";
import {
  addOrEditPickProduct,
  deletePickProduct,
  queryPickProductList,
  updatePickProductSort,
} from "@/api/business/channelManagement";
import { mapGetters } from "vuex";
import { getDownProductList } from "@/api/business/productManagement";

export default {
  name: "PickEditDialog",
  props: {
    // 弹框的默认宽度
    width: {
      type: String,
      default: "800px",
    },
    // 弹框的默认高度
    height: {
      type: String,
      default: "70%",
    },
    // 弹框的标题
    title: {
      type: String,
      default: "渠道采量限制管理",
    },
  },
  data() {
    return {
      // 弹框的显示状态
      pickDialogShow:false,
      // 表格数据
      tableData: [],
      // 表格列信息
      columns: [
        {label: `排序号`,prop: "sortNum",visible: true,pcWidth: 250,mobileWidth: 120,fixed: null,showTooltip: true,},
        {label: `产品名称`,prop: "productName",visible: true,pcWidth: 250,mobileWidth: 120,fixed: null,showTooltip: true,},
        {label: `产品限制`,prop: "isProduct",visible: true,pcWidth: 250,mobileWidth: 120,fixed: null,showTooltip: true,},
        {label: `产品限制集合`,prop: "productIds",visible: true,pcWidth: 350,mobileWidth: 100,fixed: null,showTooltip: true,},
        {label: `操作`,prop: "operation",visible: true,pcWidth: 180,mobileWidth: 100,fixed: "right",showTooltip: true},
      ],
      // 产品限制筛选项
      isProductOption:[
        { label: "无限制", value: 0 },
        { label: "排除产品", value: 1 },
        { label: "包含产品", value: 2 },
      ],
      // 表单信息
      form: {
       
      },
      // 表单校验规则
      rules: {

      },
      // 产品列表筛选项
      productIdsOption:[],
      // 添加项限制列表
      addPickList:[

      ],
      // 唯一id计数器
      idCounter: 0,
      // 添加/添加项限制参数对象
      addOreditPickQueryObj:{

      },
      // 渠道信息对象
      channelObj:{

      },
    }
  },
  created(){
     this.getProductList()
  },
  mounted() {
   
  },
  computed:{
    ...mapGetters(["device"]),
     // 计算当前列元素在所处环境的宽度
     getColumnWidth() {
      return (index,columName) => {
        return this.isMobile
          ? this[columName][index].mobileWidth
          : this?.sidebar?.opened
          ? this[columName][index]?.pcWidth - this.slightWidth
          : this[columName][index]?.pcWidth + 17;
      };
    },
    // 将数组转换为对象形式
    ArrayFormatObj:()=>{
        return (arr)=>{
          return arr.reduce((pre, cur)=>{
            pre[cur.value] = cur.label;
            return pre;
          },{})
        }
     },

  },
  methods: {
    // 产品限制改变事件
    isProductChange(value,row){
      // 如果是无限制则清除产品限制集合
      if(value === 0){
        this.$set(this.addOreditPickQueryObj[`form_'${row?.id}`],'productIds',[])
      }
    },
    // 行的拖拽
    rowDrop() {
      // 获取需要拖拽的DOM对象
      const tbody = document.querySelector(
        ".pickEdit_table .el-table__body-wrapper tbody"
      );
      //解决指向问题
      const that = this;
      //创建新实例
      Sortable.create(tbody, {
        //动画
        animation: 180,
        //延迟
        delay: 0,  
        // 结束拖拽
        onEnd({ newIndex, oldIndex }) {
          //   删除当前行，放到拖拽后的位置
          const currentRow = that.tableData.splice(oldIndex, 1)[0];
          that.tableData.splice(newIndex, 0, currentRow);
          // 判断如果有新增的自动过滤掉
          let newSortarr = that.tableData.filter(pre=>pre?.sortNum).map((item,index)=>({id:item?.id,sortNum:index + 1}))
        //   console.log('最新排序',newSortarr);
          // 提交排序接口
          updatePickProductSort(newSortarr).then((res) => {
            if(res?.code == 200){
              // 刷新列表
              that.getPickProductList()
            }
          });
          
        },
      });
    },
    // 展示弹框
    showDialog(row){
       this.$set(this,'channelObj',row)
       this.getPickProductList(); // 获取采量限制列表
       this.pickDialogShow = true;
    },
    // 获取产品筛选项列表
    getProductList(){
      // 获取下游产品列表
      getDownProductList().then((res) => {
        this.productIdsOption = res.data;
      });
    },
    // 获取采量限制列表
    getPickProductList(){
      // 获取采量限制列表
      queryPickProductList(this.channelObj.id).then((res) => {
        if(res?.code == 200){
            this.$set(this,'tableData',res.data)
            //dom加载完成触发
            this.$nextTick(() => {
              this.pickDialogShow && this.rowDrop(); // 行
            });
        }
      });
    },
    // 点击添加采量限制
    addPick() {
        let id = this.idCounter++
        // 向列表中新增一个表示可编辑的对象
        this.tableData.push({
            isProduct:undefined,
            optionType:true,
            // 操作类型(add:新增,edit编辑)
            optionType:'add',
            id: id, // 生成唯一的id,
            productName:this?.channelObj?.productName
        })
        this.$nextTick(() => {
           this.rowDrop(); // 行
        });

        // 设置一个新的参数对象
        this.$set(this.addOreditPickQueryObj,`form_'${id}`,{})
    },
    // 点击采量限制保存
    handelSave(row,query){
       console.log("参数",query);
       console.log("行信息",row);
       if(query?.isProduct && query?.isProduct ==0){
          // 如果为无限制则设置为空
          query.productIds = []
       }
       let params ={
          // 产品id
          productId:this.channelObj?.id,
          ...JSON.parse(JSON.stringify(query))
       }
       console.log(params);
       // 保存采量限制
       addOrEditPickProduct(params).then(res=>{
          if(res.code == 200){
            this.$message.success('操作成功')
            // 刷新列表
            this.getPickProductList()
          }
       })
       
    },
    // 点击采量编辑
    handelEdit(row){
       console.log(row);
       // 设置操作为编辑状态
       row.optionType = 'edit'
       // 设置一个新的参数对象
       this.$set(this.addOreditPickQueryObj,`form_'${row?.id}`,{
        ...JSON.parse(JSON.stringify(row))
       })
       
    },
     // 取消删除
     hanCancelDel(){
      this.$message({
        type: 'info',
        message: '已取消删除操作'
      });
    },
    // 删除列表项
    handelDel(row) {
      let { id } = row
      deletePickProduct(id).then(res=>{
        if(res.code === 200) {
          this.$message.success('删除成功')
          // 刷新列表
          this.getPickProductList()
        }
      })
      
    },
    // 关闭弹框事件
    handleClose(callBack) {
      // 唯一id计数器(设置默认)
      this.idCounter=0,
      this.pickDialogShow = false;
      console.log('handleClose');
      
      // 重置参数对象
      this.$set(this,'addOreditPickQueryObj',{})
      // 重置表格数据
      this.$set(this,'tableData',[])
      callBack();
    },
  },
};
</script>

<style scoped lang='scss'>
.pickEdit_dialog {
  .pickEdit_content {
    width: 100%;
    height: 78vh;
    display: flex;
    .addBtn {
      margin-right: 10px;
      width: 66px;
    }
    .pickEdit_table {
      width: calc(100% - 66px);
    }
  }
}
::v-deep ::-webkit-scrollbar {
    width: 10px; // 横向滚动条
    height: 12px; // 纵向滚动条
}
</style>